<?php

namespace App\Http\Controllers;

use DB;
use Laravel\Lumen\Routing\Controller;
use Request;
use Validator;
use Session;

use Dingo\Api\Routing\Helpers;

class TableController extends BaseController
{	
	use Helpers;
	public function __CONSTRUCT()
	{	
		if(empty(Session::get('user_id'))){
            $tableUrl = "HTTP://".$_SERVER["HTTP_HOST"];
            $this->oauth2($tableUrl."/table",env('TABLE_CLIENT_ID'));
        }
	}
	public function index()
	{	
		$param = Request::all();
        $userId = Session::get('user_id');
        $result['user_id'] = $userId;
        $isImport = DB::table('ed_import')->where('user_id',$userId)->where('object','table')->first();
        if(empty($isImport)){
        	$importResult = $this->api->post('table');
        	if($importResult['error'] == true){
		    	$state = urlencode("HTTP://".$_SERVER["HTTP_HOST"]."/table");
		        $redirectUrl  = env("OAUTH_URL")."/campus/oauth2/auth?state=$state&user_id=$userId&system_cat=edu";
		        return redirect($redirectUrl);
        	}
        }
		$weekStartArr = Config('ptime.week_start_arr');
		//教学周
		$schoolWeekArr = array_keys($weekStartArr);
		//当前周周一
		$lastMonday = date('Y-m-d',strtotime('last monday', strtotime('tomorrow')));
		//获取当前周
		$tempWeekNow = array_search($lastMonday, $weekStartArr);
		$weekInput = isset($param['week']) ? $param['week'] : $tempWeekNow;
		$result['table_week'] = $weekInput;
		//获取选中周数的周一
		$monday = $weekStartArr[$weekInput];
		//获取选中周数的周日
		$sunday = date('Y-m-d',strtotime($monday.'next sunday'));
		$startTime = strtotime($monday);
    	$endTime = strtotime($sunday);
    	//当前周所有日期
		$dateArr = [];
		while($startTime <= $endTime){
			$dateArr[] = date('m-d',$startTime);
			$startTime = strtotime("+1 day",$startTime);
		}
		$result['school_week_all'] = $schoolWeekArr;
		$result['school_week_now'] = $tempWeekNow;
		$result['week_day'] = $dateArr;
		$result['month'] = date('m');
		$result['date'] = date('m-d');
        $result['term'] = date('m',strtotime($monday)) < 8 ? 2 : 1;
        $result['school_year'] = ($result['term']==2) ? (date('Y')-1).'-'.date('Y') : date('Y').'-'.(date('Y')+1);
       	//星期
       	$weekDay = ['1','2','3','4','5','6','7'];
       	//课节
		$classDay = ['1,2','3,4','5,6','7,8','9,10','11,12'];
    	$tableDetail = DB::table('ed_record')
						->join('ed_user_record','ed_user_record.record_id','=','ed_record.id')
						->select('ed_record.*')
						->where('ed_user_record.user_id','=',$userId)
						->where('ed_record.year',$result['school_year'])
						->where('term',$result['term'])
						->orderBy('ed_record.week_n','ASC')
						->orderBy('ed_record.class_n','ASC')
						->get();
		if(empty($tableDetail)){
			$tableDetailYan = DB::table('ed_record_yan')
							->join('ed_user_record_yan','ed_user_record_yan.record_id','=','ed_record_yan.id')
							->select('ed_record_yan.*')
							->where('ed_user_record_yan.user_id','=',$userId)
							->orderBy('ed_record_yan.week_n','ASC')
							->orderBy('ed_record_yan.class_n','ASC')
							->get();
			$tableData = [];
	        //按星期排课
	        foreach ($tableDetailYan as $key => $value) {
	        	$isInTime = ($value->week_start <= $weekInput && $value->week_end >= $weekInput) ? 1 : 0;
	        	$classES = explode(',',$value->class_n);
	        	if(count($classES) == 1){
	        		switch($classES[0]){
	        			case "1":
	        				$tempClassN[0] = '1,2';
	        			break;
	        			case "2":
	        				$tempClassN[0] = '1,2';
	        			break;
	        			case "3":
	        				$tempClassN[0] = '3,4';
	        			break;
	        			case "4":
	        				$tempClassN[0] = '3,4';
	        			break;
	        			case "5":
	        				$tempClassN[0] = '5,6';
	        			break;
	        			case "6":
	        				$tempClassN[0] = '5,6';
	        			break;
	        			case "7":
	        				$tempClassN[0] = '7,8';
	        			break;
	        			case "8":
	        				$tempClassN[0] = '7,8';
	        			break;
	        			case "9":
	        				$tempClassN[0] = '9,10';
	        			break;
	        			case "10":
	        				$tempClassN[0] = '9,10';
	        			break;
	        		}
	        	}
	        	elseif(count($classES) == 4){
	        		$tempClassN[0] = $classES[0].','.$classES[1];
	        		$tempClassN[1] = $classES[2].','.$classES[3];
	        	}
	        	else{
	        		$tempClassN[0] = $classES[0].','.$classES[1];
	        	}
	        	foreach ($tempClassN as $key1 => $value1) {
	        		$tableData[ $value1.$value->week_n ][] = [
						'id'			    => $value->id,
						'class_name'		=> $value->class_name,
						'addr'				=> $value->addr,
						'academy'			=> $value->academy,
						'subject_num' 		=> $value->subject_num,
						'subject_name' 		=> $value->subject_name,
						'teacher_name' 		=> $value->teacher_name,
						'description' 		=> $value->description,					
						'week_start' 		=> $value->week_start,
						'week_end' 			=> $value->week_end,
						'week_n' 			=> $value->week_n,
						'class_n' 			=> $value->class_n,
						'class_p' 			=> $value->class_p,
						'credit' 			=> $value->credit,
						'is_degree' 		=> $value->is_degree,
						'is_intime'			=> $isInTime,
					];
	        	}	
        	}					
		}else{
			$tableData = [];
	        //按节次排课
	        foreach ($tableDetail as $key => $value) {
	        	$isInTime = ($value->week_start <= $weekInput && $value->week_end >= $weekInput) ? 1 : 0;
	        	$tableData[ $value->class_n.$value->week_n ][] = [
					'id'			    => $value->id,
					'subject_name' 		=> $value->subject_name,
					'teacher_name' 		=> $value->teacher_name,
					'addr' 				=> $value->addr,
					'week_n' 			=> $value->week_n,
					'week_start' 		=> $value->week_start,
					'week_end' 			=> $value->week_end,
					'class_n' 			=> $value->class_n,
					'others' 			=> $value->others,
					'is_intime'			=> $isInTime,
				];
        	}
		}				
        $finalData = [];
        foreach ($classDay as $class_n) {
			foreach ($weekDay as $week_n) {
				$finalData[$class_n][$week_n] = isset($tableData[$class_n.$week_n]) ? $tableData[$class_n.$week_n]:[];
			}
		}		
		$result['is_empty'] = empty($tableDetail) ? 1 : 0;
        $result['table'] = $finalData;
		return view('table/index',['result'=>$result]);
	}

	public function store()
	{	
		$param = Request::all();
        $userId = Session::get('user_id');
		//获取课程
        $header = [
        	"host:campus",
        	"authorization:".Session::get("authorization")
        ];
        $courseResult = $this->getCourse($userId,$header);
        $courseResult = json_decode($courseResult,true);
        if($courseResult['error'] == true){
        	return $this->jsonResponse(true,[],$courseResult['message']);
        }
        
        //判断用户院校
        $campusId = $courseResult['result']['row']['campus_id'];
        switch ($campusId) {
			case '1':
				$result = $this->cTable($userId,$courseResult['result']);
				break;
			case '2':
				$result = $this->cTable($userId,$courseResult['result']);
				break;
			case '3':
				$result = $this->sTable($userId,$courseResult['result']);
				break;		
			
			default:
				# code...
				break;
		}
		$this->edImport($userId,'table');
		if(isset($result['api_error'])){
			return $this->jsonResponse(true,['url'=>'/table'],'程序猿正在打瞌睡');
		}
		if($result['user_record_id'] == ''){
			return $this->jsonResponse(false,['url'=>'/table'],'少年，你本学期无课程');
		}
		return $this->jsonResponse(false,['url'=>'/table'],'导入成功');
	}
	//本科生课表
	public function cTable($user_id,$tableResult)
	{	
		//删除之前导入记录
		$deleteResult = DB::table('ed_user_record')->where('user_id',$user_id)->delete();
		//学年
		$year = $tableResult['row']['ct_info']['xn'];
		//学期
		$term = $tableResult['row']['ct_info']['xq'];
		//星期换大写
		$weekBig = Config('ptime.week_to_big');
		//校历
		$weekStartArr = Config('ptime.week_start_arr');
		//课表详情
		$tableDetail = $tableResult['data'];
		//构造暂存所有ed_record数组
		$recordMd5Arr = [];
		foreach ($tableDetail as $key => $value) {
			//课程名称
			$title  	 = $value['kc'];
			//上课地点
			$addr   	 = $value['dd'];
			//开始周
			$sWeek  	 = $value['ksz'];
			//结束周
			$eWeek 	 	 = $value['jsz'] == null ? $sWeek : $value['jsz'];
			//星期几
			$dWeek  	 = $value['xq'];
			//上课老师
			$teacherName = $value['js'];
			//第几节课
			$classNum    = $value['jc'];

			$recordMd5Arr = [
				'subject_name' => $title,
				'teacher_name' => $teacherName,
				'addr'		   => $addr,
				'week_n' 	   => $dWeek,
				'week_start'   => $sWeek,
				'week_end'     => $eWeek,
				'class_n'	   => $classNum,
				'year' 		   => $year,
				'term' 		   => $term,
			];
			$recordMd5Str = implode('-', $recordMd5Arr);
			$recordMd5 = substr(md5($recordMd5Str),8,16);
			$recordMd5Arr['id'] = $recordMd5;
			$recordMd5Arr['description'] = "每周[每周".$weekBig[$recordMd5Arr['week_n']]."]";
			//开启事务
			DB::beginTransaction();
			//判断课程记录是否存在
			$recordExist = DB::table('ed_record')->where('id',$recordMd5)->first();
			if(!$recordExist){
				$recordResult = DB::table('ed_record')->insert($recordMd5Arr);
				if(!$recordResult){
					DB::rollback();
					$result['api_error'] = 1;
					return $result;
				}
			}	
			$insertUserRecoedArr = [
				'user_id'   	=> $user_id,
				'record_id' 	=> $recordMd5,
			];
			$userRecordId = DB::table('ed_user_record')->insertGetId($insertUserRecoedArr);
			if(!$userRecordId){
				DB::rollback();
				$result['api_error'] = 1;
				return $result;
			}
			DB::commit();
		}
		$result['user_record_id'] = isset($userRecordId) ? $userRecordId : '';
		return $result;		
	}

	//研究生课表
	public function sTable($user_id,$tableResult)
	{	
		$deleteResult = DB::table('ed_user_record_yan')->where('user_id',$user_id)->delete();
		//星期换大写
		$weekBig = Config('ptime.week_to_big');
		//校历
		$weekStartArr = Config('ptime.week_start_arr');
		//课表详情
		$tableDetail = $tableResult['data'];
		foreach ($tableDetail as $key => $value) {
			//课程名称
			$title  	 = $value['kc'];
			//上课地点
			$addr   	 = $value['dd'];
			//开始周
			$sWeek  	 = $value['ksz'];
			//结束周
			$eWeek 	 	 = $value['jsz'] == null ? $sWeek : $value['jsz'];
			//星期几
			$dWeek  	 = $value['xq'];
			//上课老师
			$teacherName = $value['js'];
			//第几节课
			$classNum    = $value['jc'];

			$recordMd5Arr = [
				'subject_name' => $title,
				'teacher_name' => $teacherName,
				'addr'		   => $addr,
				'week_n' 	   => $dWeek,
				'week_start'   => $sWeek,
				'week_end'     => $eWeek,
				'class_n'	   => $classNum,
				'year' 		   => $year,
				'term' 		   => $term,
			];
			$recordMd5Str = implode('-', $recordMd5Arr);
			$recordMd5 = substr(md5($recordMd5Str),8,16);
			$recordMd5Arr['id'] = $recordMd5;
			$recordMd5Arr['description'] = "每周[每周".$weekBig[$recordMd5Arr['week_n']]."]";
			//开启事务
			DB::beginTransaction();
			//判断课程记录是否存在
			$recordExist = DB::table('ed_record_yan')->where('id',$recordMd5)->count();
			if(!$recordExist){
				$recordResult = DB::table('ed_record_yan')->insert($recordMd5Arr);
				if(!$recordResult){
					DB::rollback();
					$result['api_error'] = 1;
					return $result;
				}
			}
			$insertUserRecoedArr = [
				'user_id'   	=> $user_id,
				'record_id' 	=> $recordMd5,
				'calendar_id'   => $calendarId,
			];
			$userRecordId = DB::table('ed_user_record_yan')->insertGetId($insertUserRecoedArr);
			if(!$userRecordId){
				DB::rollback();
				$result['api_error'] = 1;
				return $result;
			}
			DB::commit();
		}
		$result['user_record_id'] = isset($userRecordId) ? $userRecordId : '';
		return $result;
	}
} 